package com.yuyou.tas.lesson.controller;

import com.yuyou.tas.lesson.service.IBaseMaterialService;
import com.yuyou.tas.lesson.service.comm.OrganLimitService;
import com.yuyou.tas.lesson.vo.req.ReqAddBaseMaterial;
import com.yuyou.tas.lesson.vo.req.ReqUpdateBaseMaterial;
import com.yuyou.tas.service.api.lesson.dto.DtoBaseMaterial;
import com.yuyou.tas.service.api.lesson.entity.BaseMaterial;
import com.yuyou.tas.util.bean.*;
import com.yuyou.tas.util.config.SystemConfig;
import com.yuyou.tas.util.enums.OrganLimitEnums;
import com.yuyou.tas.util.enums.admin.AuthUserEnums;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value="BaseMaterialController",description="素材库操作接口")
@Validated
@RestController
@RequestMapping(value="/api/baseMaterial")
public class BaseMaterialController extends BaseController {

    @Autowired
    private IBaseMaterialService service;

    @Autowired
    private OrganLimitService organLimitService;

    @ApiOperation(value="插入素材库素材")
    @RequestMapping(value="/addBaseMaterial",method = RequestMethod.POST)
    public ReturnResult addBaseMaterial(HttpServletRequest request , @Validated @ModelAttribute ReqAddBaseMaterial material){
        LoginRedisObj user = this.getUserObj(request);
        ResBoolSimpleInfo info =  service.addMaterial(material,null,
                                                        user.getIsSystem()?1:0,
                                                        user,user.getOrganizationId());
        return ReturnResult.returnRes(info.isSuccess() , info.getMessage() , null);
    }

    @ApiOperation(value="通过ID获取素材库素材")
    @RequestMapping(value="/getBaseMaterial",method = {RequestMethod.GET, RequestMethod.POST})
    public ReturnResult<BaseMaterial> getBaseMaterial(HttpServletRequest request ,
                                                      @Validated @NotNull(message = "ID不能为空")@ApiParam(value = "素材库素材ID" , required = true) @RequestParam(value = "id") Long id) throws Exception {
        LoginRedisObj user = this.getUserObj(request);
        /*if(!user.getIsSystem()) {
            organLimitService.checkOrganByOrganId(user.getOrganizationId(), id, OrganLimitEnums.type.base_material);
        }*/
        BaseMaterial material =  service.selectByPrimaryKey(id);
        //系统课程、但用户非系统管理员且所在机构没有对应科目年级权限
        if(material != null && !user.getIsSystem() && material.getAuthOrganizationId().equals(SystemConfig.SYS_ORGAN_ID)
                    && (user.getOrganSubSecMap() == null
                    || !user.getOrganSubSecMap().containsKey(material.getDataSubject())
                    || CollectionUtils.isEmpty(user.getOrganSubSecMap().get(material.getDataSubject()))
                    || !user.getOrganSubSecMap().get(material.getDataSubject()).contains(material.getBaseSectionId()))){
                return ReturnResult.returnRes(true , null , null);
        }
        return ReturnResult.returnRes(true  , null , material);
    }

    @ApiOperation(value="更新素材库素材")
    @RequestMapping(value="/updateBaseMaterial",method = RequestMethod.POST)
    public ReturnResult updateBaseMaterial(HttpServletRequest request , @Validated @ModelAttribute ReqUpdateBaseMaterial material) throws Exception {
        LoginRedisObj user = this.getUserObj(request);
        if(!user.getIsSystem()) {
            organLimitService.checkOrganByOrganId(user.getOrganizationId(), material.getId(), OrganLimitEnums.type.base_material);
        }
        ResBoolSimpleInfo info =  service.updatMaterial(material,null, user.getIsSystem()? 1:0,user);
        return ReturnResult.returnRes(info.isSuccess() , info.getMessage() , null);
    }

    @ApiOperation(value="删除素材库素材")
    @RequestMapping(value="/delBaseMaterial",method = RequestMethod.POST)
    public ReturnResult delBaseMaterial(HttpServletRequest request , @Validated @NotNull(message = "ID不能为空")@ApiParam(value = "素材库素材ID" , required = true) @RequestParam(value = "id") Long id) throws Exception {
        LoginRedisObj user = this.getUserObj(request);
        if(!user.getIsSystem()) {
            organLimitService.checkOrganByOrganId(user.getOrganizationId(), id, OrganLimitEnums.type.base_material);
        }
        ResBoolSimpleInfo info =  service.delMaterial(id);
        return ReturnResult.returnRes(info.isSuccess() , info.getMessage() , null);
    }

    @ApiOperation(value = "分页查询素材库素材")
    @RequestMapping(value = "/findBaseMaterial" ,method = {RequestMethod.GET,RequestMethod.POST})
    public ReturnResult<DtoBaseMaterial> findBaseMaterial(HttpServletRequest request,
                                                          @Validated @ModelAttribute PageParams pageParams,
                                                          @ApiParam(value = "名称")@RequestParam(value = "name",required = false) String name,
                                                          @ApiParam(value = "科目ID")@RequestParam(value = "dataSubject",required = false) String dataSubject,
                                                          @ApiParam(value = "年级ID，单个")@RequestParam(value = "baseSectionId",required = false) String baseSectionId,
                                                          @ApiParam(value = "层级ID")@RequestParam(value = "baseLevelId",required = false) String baseLevelId,
                                                          @ApiParam(value = "学期ID")@RequestParam(value = "baseTrimesterId",required = false) String baseTrimesterId,
                                                          @ApiParam(value = "获取系统数据：1、是，0或不传、否")@RequestParam(value = "getSys" , required = false)Integer getSys){
        Map<String, Object> conditions = new HashMap<>();
        Pagination<DtoBaseMaterial> queryPgn = new Pagination<>();
        LoginRedisObj user = this.getUserObj(request);

        if(!StringUtils.isEmpty(name)){
            conditions.put("name", name.trim());
        }
        if(!StringUtils.isEmpty(dataSubject)){
            conditions.put("dataSubject", dataSubject.trim());
        }/*else if(!user.getIsManager() && user.getUserType()==AuthUserEnums.type.teaching.getValue()){//教研
            conditions.put("subjectIDs", user.getDataSubjects());//获取用户科目权限
        }*/
        if(!StringUtils.isEmpty(baseSectionId)){
            conditions.put("baseSectionId", baseSectionId.trim());
        }/*else if(!user.getIsManager()){
            conditions.put("sectionIDs", user.getBaseSectionIds());//获取用户年级权限
        }*/
        if(!StringUtils.isEmpty(baseLevelId)){
            conditions.put("baseLevelId", baseLevelId.trim());
        }
        if(!StringUtils.isEmpty(baseTrimesterId)){
            conditions.put("baseTrimesterId", baseTrimesterId.trim());
        }

        if(!user.getIsManager() && user.getUserType()==AuthUserEnums.type.teaching.getValue()) {//教研-用户年纪科目权限
            conditions.put("subSecLimit" , user.getUserId());
        }

        if(getSys != null && getSys == 1){
            conditions.put("organ_id", SystemConfig.SYS_ORGAN_ID);//系统机构
            if(!user.getIsSystem()){
                //非系统管理员且查询系统课程、过滤对应机构年级科目权限
                conditions.put("permit" , user.getOrganizationId());
                /*if(CollectionUtils.isEmpty(user.getOrganSubjects()) || CollectionUtils.isEmpty(user.getOrganSectionIds())){
                    return ReturnResult.success(Pagination.getZeroPage(pageParams));
                }
                conditions.put("organSubjectLimit", user.getOrganSubjects());
                conditions.put("organSectionLimit", user.getOrganSectionIds());*/
            }
        }else {
            conditions.put("organ_id", user.getOrganizationId());//查询个人所在机构的校区
        }

        queryPgn.setConditions(conditions);
        queryPgn.setPageParams(pageParams);

        int total = service.findMaterialCount(queryPgn);
        queryPgn.setTotal(total);
        queryPgn.toBePage();
        if(total > 0){
            List<DtoBaseMaterial> list = service.findMaterialPageList(queryPgn);
            queryPgn.setList(list);
        }
        return ReturnResult.success(queryPgn);
    }
		
}
